/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.rest.service.authentication;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.rainbowsheep.reisorg.rest.service.model.BurritoRole;
import nl.rainbowsheep.reisorg.rest.service.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author ieme
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepo;

    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        nl.rainbowsheep.reisorg.rest.service.model.BurritoUser user = userRepo.findByUsername(username);
        List<GrantedAuthority> authorities = buildUserAuthority((Set<BurritoRole>) user.getBurritoUserRoles());

        return buildUserForAuthentication(user, authorities);
    }

	// Converts cnl.raindbowsheep.reisorg.rest.service.model.BurritoUser user to
    // org.springframework.security.core.userdetails.User
    private User buildUserForAuthentication(nl.rainbowsheep.reisorg.rest.service.model.BurritoUser user,
            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(),
                user.getPassword(), user.isEnabled(),
                true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<BurritoRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (BurritoRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getBurritoRole()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }
}
